package com.atguigu.tingshu.search.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2023-12-13 14:39
 */
@Slf4j
@Component
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 1.是否需要做幂等性处理 2.是否需要事务管理
     * 监听专辑上架消息，完成专辑索引库文档新增
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ALBUM_UPPER)
    public void upperAlbum(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到专辑上架：{}", value);
            searchService.upperAlbum(Long.valueOf(value));
        }
    }


    /**
     * 1.是否需要做幂等性处理 2.是否需要事务管理
     * 监听专辑下架消息，删除索引库文档
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ALBUM_LOWER)
    public void lowerAlbum(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到专辑下架：{}", value);
            searchService.lowerAlbum(Long.valueOf(value));
        }
    }

    /**
     * 监听到专辑/声音统计信息更新
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void updateStat(ConsumerRecord<String, String> record) {
        String value = record.value();
        if (StringUtils.isNotBlank(value)) {
            log.info("[搜索服务]监听到专辑/声音统计信息更新：{}", value);
            TrackStatMqVo mqVo = JSON.parseObject(value, TrackStatMqVo.class);
            searchService.updateStat(mqVo);
        }
    }
}
